/**
 * 
 */
package com.geezdata.cps.ttk.core.command;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.ttk.common.request.CreateOrUpdateGoodsRequest;
import com.geezdata.cps.ttk.common.response.CreateOrUpdateGoodsResult;
import com.geezdata.cps.ttk.domain.domain.Goods;
import com.geezdata.cps.ttk.domain.factory.GoodsFactory;
import com.geezdata.cps.ttk.mapper.mapper.GoodsMapper;

/**
 * @author sszheng
 * @date 创建时间：2018年10月29日 下午3:14:03
 *
 */
@Service
public class CreateOrUpdateGoodsCommand implements Command<CreateOrUpdateGoodsRequest, CreateOrUpdateGoodsResult> {
	@Autowired
	private GoodsMapper goodsMapper;
	
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public BaseResponse<CreateOrUpdateGoodsResult> execute(CreateOrUpdateGoodsRequest request) {
		CreateOrUpdateGoodsResult result = new CreateOrUpdateGoodsResult();
		
		Goods exsitsGoods = testIfExistGoods(request);
		Goods goods = GoodsFactory.newInstance(request, exsitsGoods);
		createOrUpdateGoods(exsitsGoods, goods);
        result.setGoodsId(goods.getGoodsId());
		
		return BaseResponse.success(result);
	}
	
	private void createOrUpdateGoods(Goods exsitsGoods, Goods goods) {
		if(exsitsGoods == null) {
			goodsMapper.insert(goods);
		} else {
			goodsMapper.updateByPrimaryKey(goods);
		}
	}

	private Goods testIfExistGoods(CreateOrUpdateGoodsRequest request) {
		Goods exsitsGoods = null;
		if(request.getGoodsReqVO().getPddGoodsId() != null) {
			Goods condition = new Goods();
			condition.setPddGoodsId(request.getGoodsReqVO().getPddGoodsId());
			exsitsGoods = goodsMapper.selectOne(condition);
		}
		return exsitsGoods;
	}
}